<template>
	<view class="container">
				<custom-status-bar></custom-status-bar>
		<!-- 头部导航 -->
		<view class="header">
			<view class="back-icon" @click="goBack">
				<uni-icons type="left" size="20" color="#1890ff"></uni-icons>
				<text>返回</text>
			</view>
			<text class="title">我的订单</text>
		</view>
		
		
	
		
		
	<!-- 	<uv-overlay :show="loading" @click="show = false" :z-index ="999" :opacity="0">
				<uv-loading-icon :show="loading"></uv-loading-icon>
			</uv-overlay> -->
		
		
		
		
		
		<!-- 订单状态标签 -->
		<uv-tabs :current="currentTab" :list="tabList" :scrollable="false" lineColor="#232773" lineWidth="30"
			@click="handleClick" @change="handleTabChange" ></uv-tabs>
			
				<uv-loading-page :loading="loading" loading-text="加载中..." font-size="24rpx"></uv-loading-page>
			
			
		<!-- 订单内容区域 -->
		<view class="content">
			<!-- 显示订单列表 -->
			<view v-if="filteredOrders.length > 0">
				<view v-for="(order, orderIndex) in filteredOrders" :key="orderIndex" class="order-item">
					<view class="order-infos">订单信息</view>
					<view class="order-info">
						<text>订单编号：{{ order[0].oid }}</text>
						<button v-if="order[0].status === 1" class="confirm-btn"
							@click="confirmOrder(order)">确认收货</button>
							
							<view class="finished" v-else>
								<text>已完成</text>
								<uv-icon size="20" name="trash" @click="deleteOrder(order[0].oid)"></uv-icon>
							</view>						
					</view>
					<view class="products">
						<view v-for="(product, productIndex) in order" :key="productIndex" class="product-item">
							<image :src="image(product)" class="product-image" />
							<view class="product-details">
									<view class="product-name-container">
								<text class="product-name">{{ product.name }}</text>
								<text class="product-spec">{{ product.rule }}</text>
									</view>
								<view class="product-english">{{ product.enname }}</view>
								<text class="price-tag">¥{{ product.price }}</text>
							</view>
							<text class="quantity">x{{ product.count }}</text>
						</view>
					</view>
					<view class="total-info">
						<view class="order-time">{{ formatDateTime(order[0].createdAt) }}</view>
						<view class="quantity-price">
							<view>共计 {{ totalQuantity(order) }} 件商品</view>
							<view class="total-price">订单金额：¥ {{ totalPrice(order)}}</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 没有订单数据时的提示 -->
			
				<uv-empty v-else  mode="order" class="center">
				</uv-empty>
	<!-- 		<view v-else class="no-data">
				<image src="/static/images/no-data.png" class="no-data-image"></image>
				<text>没有订单数据！</text>
			
			</view> -->
			
		</view>
	</view>
</template>
<script setup>
	import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getOrderStatus,confirmReceive,removeOrder
	} from "@/api/index.js"
	// 响应式数据
	
	const loading=ref(true)
	
	
	const currentTab = ref(0)
	const tabList = ref([{
		name: '全部'
	}, {
		name: '进行中'
	}, {
		name: '已完成'
	}])
	const orders = ref([])
	const fetchOrders = async (status) => {
		loading.value= true
		const res = await getOrderStatus(uni.getStorageSync('coffee_token'), status)
		if (res.code === 70000) {
			orders.value = groupByOidWithMap(res.result)
			console.log("orders:", orders.value)
		}
		loading.value= false
	}
	const groupByOidWithMap = (array) => {
		const map = new Map();
		array.forEach(item => {
			if (map.has(item.oid)) {
				map.get(item.oid).push(item);
			} else {
				map.set(item.oid, [item]);
			}
		});
		return Array.from(map.values());
	};
	// 产品图片
	const image = (item) => {
		return 'https://dummyimage.com/600x600/3c9cff/fff' || item.small_img;
	}
	// 计算属性
	const totalQuantity = (products) => {
		return products.reduce((sum, product) => sum + product.count, 0)
	};
	const totalPrice = (products) => {
		return products.reduce((sum, product) => sum + product.price * product.count, 0).toFixed(2)
	};
	onMounted(async () => {
		
		// 加载全部订单数据
		await fetchOrders(0)
		
	})
	// 计算属性：根据当前 Tab 过滤订单
	// const filteredOrders = computed(() => {
	// 	if (currentTab.value === 0) {
	// 		// 全部订单
	// 		return orders.value
	// 	} else if (currentTab.value === 1) {
	// 		// 进行中订单
	// 		// return orders.value.filter(order => order.status === 'processing')
	// 		fetchOrders(1)
	// 	} else {
	// 		// 已完成订单
	// 		// return orders.value.filter(order => order.status === 'completed')
	// 		fetchOrders(2)
	// 	}
	// })
	
	const filteredOrders = computed(()=> orders.value)
	
	
	// 方法：返回上一页
	const goBack = () => {
		const pages = getCurrentPages();
		if (pages.length > 1) uni.navigateBack();
			else  uni.switchTab({ url: '/pages/index/index' });
	}
	const handleClick = ({index,name}) => {

	}
	// 方法：处理 Tab 切换
	const handleTabChange = async({index,name}) => {

		if(index===0){
			await fetchOrders(0)
			
		}else if(index===1){
			
			 await fetchOrders(1)
		}else{
				await fetchOrders(2)
		}
		
		
		
	}
	// 方法：确认收货
	const confirmOrder = (order) => {
		// order.status = 'completed'
		// 触发重新计算
		// orders.value = [...orders.value]
		
		uni.showModal({
			title:'确认已经收到？',
			success:async(response)=>{
				if(response.confirm){
					const res = await confirmReceive(uni.getStorageSync('coffee_token'),order[0].oid)
					// console.log("res:",res)
					if(res.code === 80000){			  
					   uni.showToast({
							title:res.msg
					    })			  
					}
				}	
			},
			complete:()=>{
					// 刷新订单
					if(currentTab.value === 0){				
					    fetchOrders(0)				
					}else if(currentTab.value === 1){
						 fetchOrders(1)
					}
			}
		})
			
	}
	
	// 时间格式化
	const  formatDateTime =(isoString)=> {
	    // 创建Date对象
	    const date = new Date(isoString);
	    
	    // 获取各个时间组件
	    const year = date.getFullYear();
	    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
	    const day = String(date.getDate()).padStart(2, '0');
	    const hours = String(date.getHours()).padStart(2, '0');
	    const minutes = String(date.getMinutes()).padStart(2, '0');
	    const seconds = String(date.getSeconds()).padStart(2, '0');
	    
	    // 组合成目标格式
	    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
	
	// 方法 删除订单
	const deleteOrder = (oid)=>{
		
		uni.showModal({
			title:'删除该订单吗？',
			content:'订单删除后无法恢复！',
			success:async(response)=>{
				if(response.confirm){
					const res = await removeOrder(uni.getStorageSync('coffee_token'),oid)
					console.log("删除订单",res)
						if(res.code === 90000){
							uni.showToast({
								title:res.msg
							})
						}
					
						
				}	
			},
			complete:async()=>{
				// 刷新订单
				if(currentTab.value === 0){
				  await	fetchOrders(0)
				}else if(currentTab.value === 2){
					await fetchOrders(2)
				}
			}
		})
		
	}
	
	
	
	
	// 页面加载时的处理
	onLoad((options) => {
		// 可以在这里处理页面参数
		console.log('订单页面加载', options)
	})
</script>
<style scoped>
	.container {
		position: relative;
		padding-bottom: 100rpx;
	}

	.header {
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100rpx;
		border-bottom: 1rpx solid #eee;
	}

	.back-icon {
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		display: flex;
		align-items: center;
		font-size: 28rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
	}

	/* Tab 样式 */
	:deep(.uv-tabs) {
		margin-bottom: 20rpx;
	}

	:deep(.uv-tabs__item) {
		font-size: 30rpx;
	}
	
	:deep(.uv-loading-page){
		margin-top: 200rpx;
	}
	
	
	
	

	/* 订单内容样式 */
	.content {
		position: relative;
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 20rpx;
		min-height:calc(100vh - 100rpx - 44px);
	}

	.order-item {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: #fafafa;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.order-infos {
		padding-bottom: 20rpx;
		font-size: 30rpx;
		font-weight: bold;
	}

	.order-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		font-size: 28rpx;
	}

	.confirm-btn {
		background-color: #232773;
		color: #ffffff;
		border-radius: 10rpx;
		font-size: 24rpx;
		border: none;
		margin-right: 0;
		/* padding: 10rpx 20rpx; */
	}

 .finished{
	 display: flex;
	 align-items: center;
	 
 }
 
 .finished text{
	 margin-right: 10rpx;
 }


	.products {
		margin-top: 20rpx;
	}

	.product-item {
		display: flex;
	
		align-items: flex-end;
		margin-bottom: 20rpx;
	}

	.product-image {
		width: 150rpx;
		height: 150rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
	}

	.product-details {
		flex: 1;
		height: 150rpx;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;

	}
	
	
	.product-name-container {
			display: flex;
			align-items: center;
		justify-content: flex-start;
		}
	
	
	

	.product-name {
		font-size: 28rpx;
		font-size: 28rpx;
			margin-right: 30rpx;
			/* flex: 1; */
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
	}

	.product-spec {
		font-size: 24rpx;
		color: #999;
		/* margin-bottom: 10rpx; */
				white-space: nowrap;
	}

	.product-english {
		font-size: 24rpx;
		color: #999;
		/* margin-bottom: 10rpx; */
	    margin-top: 10rpx;
	}

	.price-tag {
		color: red;
		font-weight: bold;
		font-size: 28rpx;
		margin-bottom: 10rpx;
		margin-top: auto;
	}

	.quantity {
		font-size: 28rpx;
		color: #666;
		margin-left: auto;
		margin-top: auto;
	}

	.total-info {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: center;
		margin-top: 20rpx;
	}

	.order-time {
		font-size: 24rpx;
		color: #333;
		margin: 30rpx 0;
		padding-top:30rpx ;
		width: 100%;
		border-top:0.5px solid #eee;
	}
	
	.quantity-price{
		font-size: 28rpx;
		display: flex;
		    align-content: center;
		    align-items: center;
		    width: 100%;
		    justify-content: space-between;
			color:#aaa;
	}
	
	

	.total-price {
		color: red;
		font-weight: bold;
		font-size: 28rpx;
	}

	/* 没有订单数据提示 */
	.no-data {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 600rpx;
		text-align: center;
	}

	.no-data-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}

	.no-data text {
		font-size: 32rpx;
		color: #999999;
	}
	
	.center {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 160px;
		height: 160px;
	}
</style>